package com.laboratory.miniolearning.config;

import com.laboratory.miniolearning.properties.MinioProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class MinioInitializer {

    private final MinioClient minioClient;

    private final MinioProperties props;

    @PostConstruct
    public void initBucket() {
        try {
            boolean exists = minioClient.bucketExists(
                    BucketExistsArgs.builder().bucket(props.getBucket()).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(props.getBucket()).build());
            }
            if (props.getPublicRead()) {
                String policy = """
                        {
                          "Version": "2012-10-17",
                          "Statement": [{
                            "Effect": "Allow",
                            "Principal": {"AWS": ["*"]},
                            "Action": ["s3:GetObject"],
                            "Resource": ["arn:aws:s3:::%s/*"]
                          }]
                        }""".formatted(props.getBucket());
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                        .bucket(props.getBucket())
                        .config(policy)
                        .build());
            }
        } catch (Exception e) {
            throw new RuntimeException("Init MinIO bucket failed", e);
        }
    }

}
